'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  IconUsers,
  IconUserPlus,
  IconEdit,
  IconTrash,
  IconEye,
  IconEyeOff,
  IconSearch,
  IconRefresh,
  IconShield,
  IconBuilding,
  IconMail,
  IconPhone
} from "@tabler/icons-react"
import { UserManager, User, AuthManager } from '@/lib/users'
import { UserRole, RoleDisplayNames, PermissionChecker } from '@/jjk/Permissions'

export default function UserManagement() {
  const [users, setUsers] = useState<User[]>([])
  const [filteredUsers, setFilteredUsers] = useState<User[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedRole, setSelectedRole] = useState<UserRole | 'all'>('all')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  // 新用户表单状态
  const [isCreateFormOpen, setIsCreateFormOpen] = useState(false)
  const [newUser, setNewUser] = useState({
    username: '',
    password: '',
    name: '',
    role: UserRole.NURSE,
    department: '',
    position: '',
    email: '',
    phone: ''
  })

  // 编辑用户状态
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [showPassword, setShowPassword] = useState(false)

  const currentUser = AuthManager.getCurrentUser()

  // 检查权限
  const canManageUsers = currentUser?.role === UserRole.SUPER_ADMIN

  // 加载用户数据
  useEffect(() => {
    loadUsers()
  }, [])

  // 过滤用户
  useEffect(() => {
    let filtered = users

    // 按搜索词过滤
    if (searchTerm) {
      filtered = filtered.filter(user =>
        user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.department?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.position?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }

    // 按角色过滤
    if (selectedRole !== 'all') {
      filtered = filtered.filter(user => user.role === selectedRole)
    }

    setFilteredUsers(filtered)
  }, [users, searchTerm, selectedRole])

  const loadUsers = () => {
    setIsLoading(true)
    try {
      const allUsers = UserManager.getAllUsers()
      setUsers(allUsers)
    } catch (err) {
      setError('加载用户数据失败')
    } finally {
      setIsLoading(false)
    }
  }

  const handleCreateUser = () => {
    if (!canManageUsers) {
      setError('权限不足')
      return
    }

    setError('')
    setSuccess('')

    // 验证表单
    if (!newUser.username || !newUser.password || !newUser.name || !newUser.department || !newUser.position) {
      setError('请填写所有必填字段')
      return
    }

    if (!UserManager.isUsernameAvailable(newUser.username)) {
      setError('用户名已存在')
      return
    }

    try {
      const createdUser = UserManager.createUser(newUser)
      setSuccess(`用户 ${createdUser.name} 创建成功`)
      setIsCreateFormOpen(false)
      setNewUser({
        username: '',
        password: '',
        name: '',
        role: UserRole.NURSE,
        department: '',
        position: '',
        email: '',
        phone: ''
      })
      loadUsers()
    } catch (err) {
      setError('创建用户失败')
    }
  }

  const handleUpdateUser = () => {
    if (!canManageUsers || !editingUser) {
      setError('权限不足或数据错误')
      return
    }

    setError('')
    setSuccess('')

    try {
      const updatedUser = UserManager.updateUser(editingUser.id, editingUser)
      if (updatedUser) {
        setSuccess(`用户 ${updatedUser.name} 更新成功`)
        setEditingUser(null)
        loadUsers()
      } else {
        setError('更新用户失败')
      }
    } catch (err) {
      setError('更新用户失败')
    }
  }

  const handleDeactivateUser = (userId: string, userName: string) => {
    if (!canManageUsers) {
      setError('权限不足')
      return
    }

    if (window.confirm(`确定要禁用用户 "${userName}" 吗？`)) {
      try {
        const success = UserManager.deactivateUser(userId)
        if (success) {
          setSuccess(`用户 ${userName} 已禁用`)
          loadUsers()
        } else {
          setError('禁用用户失败')
        }
      } catch (err) {
        setError('禁用用户失败')
      }
    }
  }

  const getUserStats = () => {
    return UserManager.getUserStats()
  }

  const getRoleColor = (role: UserRole) => {
    switch (role) {
      case UserRole.SUPER_ADMIN:
        return 'bg-red-100 text-red-800'
      case UserRole.DEAN:
        return 'bg-purple-100 text-purple-800'
      case UserRole.DIRECTOR:
        return 'bg-blue-100 text-blue-800'
      case UserRole.DOCTOR:
        return 'bg-green-100 text-green-800'
      case UserRole.NURSE:
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  if (!canManageUsers) {
    return (
      <div className="text-center py-12">
        <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <IconShield className="w-8 h-8 text-red-500" />
        </div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">权限不足</h3>
        <p className="text-gray-500">只有超级管理员可以访问用户管理功能</p>
      </div>
    )
  }

  const stats = getUserStats()

  return (
    <div className="space-y-6">

      {/* 用户统计 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-6">
        <Card className="border-blue-200 bg-blue-50">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-blue-600">总用户数</p>
                <p className="text-2xl font-bold text-blue-700">{stats.total}</p>
              </div>
              <IconUsers className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        {Object.entries(stats.byRole).map(([role, count]) => (
          <Card key={role} className="border-gray-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">{RoleDisplayNames[role as UserRole].zh}</p>
                  <p className="text-2xl font-bold text-gray-700">{count}</p>
                </div>
                <Badge className={getRoleColor(role as UserRole)}>
                  {RoleDisplayNames[role as UserRole].zh}
                </Badge>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 操作提示 */}
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {success && (
        <Alert className="border-green-200 bg-green-50">
          <AlertDescription className="text-green-700">{success}</AlertDescription>
        </Alert>
      )}

      {/* 用户管理界面 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>用户列表</CardTitle>
              <CardDescription>查看和管理系统用户</CardDescription>
            </div>
            <div className="flex items-center space-x-2">
              <Button
                onClick={loadUsers}
                variant="outline"
                size="sm"
                disabled={isLoading}
              >
                <IconRefresh className="w-4 h-4 mr-2" />
                刷新
              </Button>
              <Button
                onClick={() => setIsCreateFormOpen(true)}
                size="sm"
              >
                <IconUserPlus className="w-4 h-4 mr-2" />
                新建用户
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* 搜索和过滤 */}
          <div className="flex items-center space-x-4 mb-6">
            <div className="flex-1 relative">
              <IconSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="搜索用户名、姓名、科室..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <select
              value={selectedRole}
              onChange={(e) => setSelectedRole(e.target.value as UserRole | 'all')}
              className="px-3 py-2 border border-gray-300 rounded-md bg-white"
            >
              <option value="all">所有角色</option>
              {Object.values(UserRole).map(role => (
                <option key={role} value={role}>
                  {RoleDisplayNames[role].zh}
                </option>
              ))}
            </select>
          </div>

          {/* 用户表格 */}
          <div className="border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户信息</TableHead>
                  <TableHead>角色</TableHead>
                  <TableHead>科室职位</TableHead>
                  <TableHead>联系方式</TableHead>
                  <TableHead>最后登录</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredUsers.map((user) => (
                  <TableRow key={user.id}>
                    <TableCell>
                      <div className="flex items-center space-x-3">
                        <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                          {user.name.charAt(0)}
                        </div>
                        <div>
                          <div className="font-medium">{user.name}</div>
                          <div className="text-sm text-gray-500">{user.username}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getRoleColor(user.role)}>
                        {RoleDisplayNames[user.role].zh}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div className="font-medium">{user.department}</div>
                        <div className="text-sm text-gray-500">{user.position}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {user.email && (
                          <div className="flex items-center text-sm text-gray-600">
                            <IconMail className="w-3 h-3 mr-1" />
                            {user.email}
                          </div>
                        )}
                        {user.phone && (
                          <div className="flex items-center text-sm text-gray-600">
                            <IconPhone className="w-3 h-3 mr-1" />
                            {user.phone}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm text-gray-500">
                        {user.lastLoginAt 
                          ? new Date(user.lastLoginAt).toLocaleString('zh-CN')
                          : '从未登录'
                        }
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setEditingUser(user)}
                        >
                          <IconEdit className="w-3 h-3" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeactivateUser(user.id, user.name)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <IconTrash className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {filteredUsers.length === 0 && (
            <div className="text-center py-8 text-gray-500">
              没有找到符合条件的用户
            </div>
          )}
        </CardContent>
      </Card>

      {/* 创建用户对话框 */}
      {isCreateFormOpen && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-md">
            <CardHeader>
              <CardTitle>创建新用户</CardTitle>
              <CardDescription>添加新的系统用户</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="username">用户名 *</Label>
                  <Input
                    id="username"
                    value={newUser.username}
                    onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
                    placeholder="请输入用户名"
                    autoComplete="username"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="name">姓名 *</Label>
                  <Input
                    id="name"
                    value={newUser.name}
                    onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
                    placeholder="请输入姓名"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="password">密码 *</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? 'text' : 'password'}
                    value={newUser.password}
                    onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                    placeholder="请输入密码"
                    autoComplete="new-password"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-0 top-0 h-full px-3"
                  >
                    {showPassword ? <IconEyeOff className="w-4 h-4" /> : <IconEye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="role">角色 *</Label>
                <select
                  id="role"
                  value={newUser.role}
                  onChange={(e) => setNewUser({ ...newUser, role: e.target.value as UserRole })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md bg-white"
                >
                  {Object.values(UserRole).map(role => (
                    <option key={role} value={role}>
                      {RoleDisplayNames[role].zh}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="department">科室 *</Label>
                  <Input
                    id="department"
                    value={newUser.department}
                    onChange={(e) => setNewUser({ ...newUser, department: e.target.value })}
                    placeholder="如：内科"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="position">职位 *</Label>
                  <Input
                    id="position"
                    value={newUser.position}
                    onChange={(e) => setNewUser({ ...newUser, position: e.target.value })}
                    placeholder="如：主治医师"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={newUser.email}
                  onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                  placeholder="请输入邮箱地址"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="phone">电话</Label>
                <Input
                  id="phone"
                  value={newUser.phone}
                  onChange={(e) => setNewUser({ ...newUser, phone: e.target.value })}
                  placeholder="请输入电话号码"
                />
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <Button variant="outline" onClick={() => setIsCreateFormOpen(false)}>
                  取消
                </Button>
                <Button onClick={handleCreateUser}>
                  创建用户
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 编辑用户对话框 */}
      {editingUser && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-md">
            <CardHeader>
              <CardTitle>编辑用户</CardTitle>
              <CardDescription>修改用户信息</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="edit-username">用户名</Label>
                  <Input
                    id="edit-username"
                    value={editingUser.username}
                    disabled
                    className="bg-gray-50"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-name">姓名</Label>
                  <Input
                    id="edit-name"
                    value={editingUser.name}
                    onChange={(e) => setEditingUser({ ...editingUser, name: e.target.value })}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-role">角色</Label>
                <select
                  id="edit-role"
                  value={editingUser.role}
                  onChange={(e) => setEditingUser({ ...editingUser, role: e.target.value as UserRole })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md bg-white"
                >
                  {Object.values(UserRole).map(role => (
                    <option key={role} value={role}>
                      {RoleDisplayNames[role].zh}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="edit-department">科室</Label>
                  <Input
                    id="edit-department"
                    value={editingUser.department || ''}
                    onChange={(e) => setEditingUser({ ...editingUser, department: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-position">职位</Label>
                  <Input
                    id="edit-position"
                    value={editingUser.position || ''}
                    onChange={(e) => setEditingUser({ ...editingUser, position: e.target.value })}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-email">邮箱</Label>
                <Input
                  id="edit-email"
                  type="email"
                  value={editingUser.email || ''}
                  onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-phone">电话</Label>
                <Input
                  id="edit-phone"
                  value={editingUser.phone || ''}
                  onChange={(e) => setEditingUser({ ...editingUser, phone: e.target.value })}
                />
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <Button variant="outline" onClick={() => setEditingUser(null)}>
                  取消
                </Button>
                <Button onClick={handleUpdateUser}>
                  保存更改
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}